#include "chessgui.h"
#include "images.h"
#include "QPainter"

namespace view
{
    ChessGUI::Square::Square(const model::Location& l) : currState(DEFAULT), img(NULL), loc(l)
    {
        setAutoFillBackground(true);
        setMinimumSize(50, 50);
        QPalette* p = new QPalette();
        p->setColor(QPalette::Window, (l.col + l.row) % 2 == 0 ? QColor(80, 80, 80) : QColor(230, 230, 230));
        setPalette(*p);
    }

    ChessGUI::SquareState ChessGUI::Square::getState() const
    {
        return currState;
    }

    void ChessGUI::Square::setState(ChessGUI::SquareState state)
    {
        currState = state;
        update();
    }

    void ChessGUI::Square::setPiece(const globals::cPiece& p)
    {
        piece = p;
        img = view::piece::getPieceImage(piece);
        update();
    }

    const globals::cPiece& ChessGUI::Square::getPiece() const
    {
        return piece;
    }

    const QImage ChessGUI::Square::act(":/cellActive"), ChessGUI::Square::capt(":/cellCapture"), ChessGUI::Square::highl(":/cellHighlight");

    void ChessGUI::Square::paintEvent(QPaintEvent*)
    {
        QPainter p(this);
        const QImage* draw;
        switch (currState)
        {
        case ACTIVE:
            draw = &Square::act;
            break;
        case HIGHLIGHT:
            draw = (piece ? &Square::capt : &Square::highl);
            break;
        }
        if (draw)
            p.drawImage((width() - height()) / 2, 0, draw->scaledToHeight(height()));
        if (img)
        {
            QImage tmp = img->scaledToHeight(height());
            p.drawImage((width() - tmp.width()) / 2, 0, tmp);
        }
    }

}
